package view;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import controller.Contact;
import controller.GUIController;

@SuppressWarnings("serial")
public class ChatList extends JList {
	
	public ChatList(DefaultListModel model)
	{
		super( model );
		
		this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		this.setLayoutOrientation(JList.VERTICAL);
		
		ListSelectionModel listSelectionModel = this.getSelectionModel();
		listSelectionModel.addListSelectionListener( new ContactListSelectionHandler(this) );
	}
	
	private class ContactListSelectionHandler implements ListSelectionListener {
	    
		private JList list;
		
		public ContactListSelectionHandler(JList l)
		{
			this.list = l;
		}
		
		public void valueChanged(ListSelectionEvent e)
	    {
			if( e.getValueIsAdjusting() )
			{
		        ListSelectionModel lsm = (ListSelectionModel)e.getSource();
		        
		        GUIController guicontroller = GUIController.getInstance();
		        
		        if ( lsm.isSelectedIndex( lsm.getMinSelectionIndex() ) )
		        {
		        	Contact c = (Contact) list.getSelectedValue();
		        	guicontroller.gui.getChatScreen().openNewDiscussion(c);
		        }
			}
	    }
	}
}
